package com.lntea.zookeeper;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.junit.Test;

public class BaseOperation {
    
    private static final int SESSION_TIMEOUT = 2000;

    @Test
    public void baseOperation() throws IOException, KeeperException, InterruptedException{
        //打开连接
        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", SESSION_TIMEOUT, new Watcher() {
            
            public void process(WatchedEvent event) {
                System.out.println("trigger " + event.getType() + " event");
            }
        });
        
        if(zk.exists("/zkdemo/child", true)!=null){
            //删除目录子节点
            zk.delete("/zkdemo/child", -1);
        }
        if(zk.exists("/zkdemo/child2", true)!=null){
            //删除目录子节点2
            zk.delete("/zkdemo/child2", -1);
        }
        if(zk.exists("/zkdemo", true)!=null){
            //删除目录节点
            zk.delete("/zkdemo", -1);
        }
        
        //创建目录节点
        zk.create("/zkdemo", "zkdemo".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //创建子目录节点
        zk.create("/zkdemo/child", "zkdemo child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //获取目录节点信息
        String zkdemoData = new String(zk.getData("/zkdemo", true, null));
        System.out.println("path /zkdemo data:"+zkdemoData);
        //获取目录子节点信息
        String zkdemoChildData = new String(zk.getData("/zkdemo/child", true, null));
        System.out.println("path /zkdemo/child data:" + zkdemoChildData);
        //获取目录子节点列表
        List<String> children = zk.getChildren("/zkdemo", true);
        System.out.println("path /zkdemo children:" + children);
        //修改目录子节点
        zk.setData("/zkdemo/child", "zkdemo child update".getBytes(), -1);
        //目录节点状态
        System.out.println("path /zkdemo exist status:" + zk.exists("/zkdemo", true));
        //增加第二个目录子节点
        zk.create("/zkdemo/child2", "zkdemo child2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //获取第二个目录子节点信息
        String zkdemoChild2Data = new String(zk.getData("/zkdemo/child2", true, null));
        System.out.println("path /zkdemo/child2 data:"+zkdemoChild2Data);
        //删除目录子节点1
        zk.delete("/zkdemo/child", -1);
        //删除目录子节点2
        zk.delete("/zkdemo/child2", -1);
        //删除目录节点
        zk.delete("/zkdemo", -1);
        //关闭连接
        zk.close();
    }
}
